<template>
  <el-dialog title="添加试卷" :visible="dialogVisible" @close="handleClose()" width="90%" class="scrollbar" fullscreen>
    <div>
      <div>
        <el-form :model="paper" ref="paper" :rules="rules">
          <el-form-item label="卷名" label-width="120" prop="planName">
            <el-input v-model="paper.planName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="及格分" label-width="120" prop="passScore">
            <el-input-number v-model="paper.passScore" :step="1"></el-input-number>
          </el-form-item>
          <el-form-item label="试卷备注" label-width="120">
            <el-input v-model="paper.remark" autocomplete="off" type="textarea"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-row :gutter="24">
          <el-col :span="6" style="display: flex; align-items: center; justify-content: cenetr">
            <h2>课件信息</h2>
            <el-select style="margin-left: 50px" placeholder="请选择题库" v-model="paper.professionId"
              @change="getSectionList(paper.professionId)">
              <el-option v-for="item, index in quBank" :key="item.index" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-col>
          <el-col :span="8" style="display: flex; align-items: center; justify-content: cenetr">
            <h2>题目信息</h2>
            <el-select style="margin-left: 30px" v-model="paper.createType" placeholder="请选择组题方式"
              @change="showQusiton = !showQusiton">
              <el-option label="手动" value="手动"></el-option>
              <el-option label="随机 " value="随机"></el-option>
            </el-select>
            <el-select v-if="paper.createType == '随机'" style="margin-left: 5px" v-model="paper.questionNum"
              placeholder="请选择组题方式">
              <el-option label="5" value="5"></el-option>
              <el-option label="10" value="10"></el-option>
              <el-option label="20" value="20"></el-option>
              <el-option label="30" value="30"></el-option>
              <el-option label="40" value="40"></el-option>
              <el-option label="50" value="50"></el-option>
              <el-option label="60" value="60"></el-option>
            </el-select>
          </el-col>
          <el-col :span="5" style="display: flex; align-items: center; justify-content: cenetr">
            <el-statistic group-separator="," :value="checkCour.length" title="已选课件"></el-statistic>
          </el-col>
          <el-col :span="5">
            <el-statistic group-separator="," :value="checkQu.length" title="已选题目"></el-statistic>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <div style="display: flex">
          <div>
            <div class="chapter">
              <span :class="chapterId == item.sectionId ? 'active' : ''" v-for="(item, index) in sectionList"
                :key="index" @click="changeChapter(item.sectionId)">
                {{ item.sectionName }}
              </span>
            </div>
          </div>
          <div style="width: 600px; margin-left: 50px">
            <el-table class="course-table" style="height: 500px; overflow-y: scroll" :data="courseList" border
              @select-all="handleSelectionAll" ref="multipleTable">
              <el-table-column prop="courseName" label="待选课件">
              </el-table-column>
              <el-table-column label="操作" align="center" width="100px">
                <template slot-scope="scope">
                  <el-button @click="preview(scope.row)" type="text" size="small">预览</el-button>
                  <el-button @click="addCourse(scope.row)" type="text" size="small"
                    :disabled="isCourseAdded(scope.row)"> {{ isCourseAdded(scope.row) ? '已添加' : '添加' }}</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="
              display: flex;
              justify-content: center;
              align-items: center;
              margin-left: 50px;
            ">
            <i class="el-icon-d-arrow-left"></i>
            <i class="el-icon-d-arrow-right"></i>
          </div>
          <div style="width: 600px; margin-left: 50px">
            <el-table :data="checkCour" border style="height: 500px; overflow-y: scroll" ref="multipleTable">
              <el-table-column prop="courseName" label="已选课件">
              </el-table-column>
              <el-table-column label="操作" align="center" width="100px">
                <template slot-scope="scope">
                  <el-button @click="removeCourse(scope.row)" type="text" size="small">移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <div>
        <el-divider></el-divider>
        <div style="display: flex" v-if="!showQusiton">
          <div style="width: 600px;">
            <el-table class="course-table" style="height: 500px; overflow-y: scroll" :data="questionList" border
              @select-all="handleSelectionAll2" ref="multipleTable">
              <el-table-column prop="questionName" label="待选题目">
              </el-table-column>
              <el-table-column prop="questionType" label="题目类型">
                <template slot-scope="scope">
                  <span v-if="scope.row.questionType === 1">单选题</span>
                  <span v-else-if="scope.row.questionType === 2">判断题</span>
                  <span v-else>多选题</span> <!-- You can add more types as needed -->
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="100px">
                <template slot-scope="scope">
                  <el-button @click="addQuesiton(scope.row)" type="text" size="small"
                    :disabled="isQuestionAdded(scope.row)"> {{ isQuestionAdded(scope.row) ? '已添加' : '添加' }}</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="
              display: flex;
              justify-content: center;
              align-items: center;
              margin-left: 50px;
            ">
            <i class="el-icon-d-arrow-left"></i>
            <i class="el-icon-d-arrow-right"></i>
          </div>
          <div style="width: 600px; margin-left: 50px">
            <el-table :data="checkQu" border style="height: 500px; overflow-y: scroll" ref="multipleTable">
              <el-table-column prop="questionName" label="已选题目">
              </el-table-column>
              <el-table-column label="操作" align="center" width="100px">
                <template slot-scope="scope">
                  <el-button @click="removeQuestion(scope.row)" type="text" size="small">移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="savePaper('paper')">确 定</el-button>
    </div>
    <PreviewVideo ref="previewVideo"></PreviewVideo>
  </el-dialog>
</template>

<script>
import { queryBankAll } from "@/api/common/index";
import { savePaper } from "@/api/onlineQuestion/index.js";
import { queryQuAll } from "@/api/question/index.js";
import { getProfessionList } from "@/api/profession/index.js";
import { getSectionList, getCourseList, queryCourseByIds } from "@/api/course/index.js";
import { addPlan, updatePlan } from "@/api/train/index.js";
import PreviewVideo from "@/components/Course/PreviewVideo";
import { getQuestionList, getQuestionListIds } from "@/api/question/index";
export default {
  components: {
    PreviewVideo,
  },
  data() {
    return {
      // 默认选中章节
      chapterId: 0,
      sectionList: [],
      courseList: [],
      questionList: [],
      tableData: [],
      showQusiton: true,
      paper: {
        planName: "",
        questionNum: 5,
        paperMark: "",
        quBankId: 1,
        professionId: 1,
        quIds: [],
        totalScore: 100,
        passScore: 60,
        createType: "随机",
      },
      quBank: [],
      formLabelWidth: "120",
      dialogVisible: false,
      courseIds: "",
      // 已选的全部课件
      checkCour: [],
      checkQu: [],
      rules: {
        planName: [
          { required: true, message: "请输入试卷名称", trigger: "blur" },
          {
            min: 1,
            max: 100,
            message: "长度在 1 到 100 个字符",
            trigger: "blur",
          },
        ],
        totalScore: [
          { required: true, message: "请填写试卷总分", trigger: "blur" },
        ],
        passScore: [
          { required: true, message: "请填写试卷及格分数", trigger: "blur" },
        ],
      },
    };
  },
  mounted() { },
  watch: {
    checkCour(val) {
      console.log(val);
      //刷新题目
      this.getQuestionList();
    },
  },

  methods: {
    getRowKeys(row) {
      return row.courseId;
    },
    //添加课件
    addCourse(row) {
      let flag = this.checkCour.some((item) => item.courseId == row.courseId);
      if (!flag) {
        this.checkCour.push(row);
      }
    },
    // New method to check if course is already added
    isCourseAdded(row) {
      return this.checkCour.some((item) => item.courseId === row.courseId);
    },
    isQuestionAdded(row) {
      return this.checkQu.some((item) => item.questionId === row.questionId);
    },
    //添加题目
    addQuesiton(row) {
      let flag = this.checkQu.some((item) => item.questionId == row.questionId);
      if (!flag) {
        this.checkQu.push(row);
      }
    },
    removeCourse(row) {
      this.checkCour = this.checkCour.filter(
        (item) => item.courseId !== row.courseId
      );
    },

    removeQuestion(row) {
      this.checkQu = this.checkQu.filter(
        (item) => item.questionId !== row.questionId
      );
    },
    //全选
    handleSelectionAll(row) {
      row.forEach((r) => {
        //如果里面已经存在这个元素，需要删除它，否则就添加到数组中
        let flag = this.checkCour.some((item) => item.courseId == r.courseId);
        console.log(flag);
        if (!flag) {
          this.checkCour.push(r);
        }
      });
    },

    //全选
    handleSelectionAll2(row) {
      row.forEach((r) => {
        //如果里面已经存在这个元素，需要删除它，否则就添加到数组中
        let flag = this.checkQu.some((item) => item.questionId == r.questionId);
        console.log(flag);
        if (!flag) {
          this.checkQu.push(r);
        }
      });
    },
    //获取章节列表
    getSectionList(professionId) {
      getSectionList({
        professionId: professionId,
      }).then((res) => {
        console.log(res);
        this.sectionList = res.rows;
        // 默认选中第一行
        if (this.sectionList.length > 0) {
          this.chapterId = this.sectionList[0].sectionId; // 选中第一行
        } else {
          this.chapterId = null; // 如果没有章节，设置为 null
        }
        this.getCourseList(this.chapterId);
      });
    },
    //获得课件列表
    getCourseList(id) {
      getCourseList({
        sectionId: id,
      }).then((res) => {
        this.courseList = res.rows;
        if (res.rows.length > 0) {
          this.$nextTick(() => {
            //判断是否需要勾选
            this.courseList.map((item, index) => {
              this.checkCour.forEach((row) => {
                if (item.courseId == row.courseId) {
                  this.$refs.multipleTable.toggleRowSelection(item, true);
                }
              });
            });
          });
        }
      });
    },
    //获取题目列表
    async getQuestionList() {
      let ids = this.checkCour
        .map(function (item) {
          return item.courseId;
        })
        .join(",");
      const res = await getQuestionList({
        courseIds: ids,
        pageSize: 10000,
        pageNum: 1,
      });
      this.questionList = res.rows;
      if (res.rows.length > 0) {
        this.$nextTick(() => {

          //判断是否需要勾选
          this.questionList.map((item, index) => {
            this.checkQu.forEach((row) => {
              if (item.questionId == row.questionId) {
                this.$refs.multipleTable.toggleRowSelection(item, true);
              }
            });
          });
        });
      }
    },
    //预览课件
    preview(item) {
      //打开弹窗
      this.$refs.previewVideo.show(item.courseUrl);
    },
    // 切换章节
    changeChapter(id) {
      if (this.chapterId != 0 && this.chapterId == id) {
        this.chapterId = 0;
      } else {
        this.chapterId = id;
      }
      this.getCourseList(id);
    },



    //选择题目
    selectQuestion() {
      if (this.checkCour.length == 0) {
        this.$modal.msgError("请选择课件");
        return;
      }
      this.$refs.SelectQuestionRef.show(this.checkCour);
    },
    //已选课件
    SelectCourse() {
      this.$refs.SelectCourseRef.show(this.checkCour);
    },
    //新增试卷
    savePaper(formName) {
      if (this.checkParams()) {
        return
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.paper.courseIds = this.checkCour
            .map(function (item) {
              return item.courseId;
            })
            .join(",");
          this.paper.questionIds = this.checkQu
            .map(function (item) {
              return item.questionId;
            })
            .join(",");
          if (this.paper.planId) {
            updatePlan(JSON.stringify(this.paper)).then((res) => {
              if (res.code == 200) {
                //关闭表单
                this.handleClose();
                //刷新父页面
                this.$parent.queryPaperList();
              }
            });
          } else {
            addPlan(JSON.stringify(this.paper)).then((res) => {
              if (res.code == 200) {
                //关闭表单
                this.handleClose();
                //刷新父页面
                this.$parent.queryPaperList();
              }
            });
          }
          this.clearData();
        } else {
          this.$modal.msgError('请检查填写信息！');
          window.scroll(0, 0);
          return false;
        }
      });
    },

    checkParams() {
      let flag = false;
      if (this.checkCour.length == 0) {
        this.$modal.msgError("请选择课件");
        flag = true
      }
      if (this.paper.createType == '手动' && this.checkQu.length == 0) {
        this.$modal.msgError("请选择题目");
        flag = true
      }
    },
    //显示弹窗
    show(row) {
      console.log(row)
      if (row) {
        this.dialogVisible = true;
        // 回显数据
        this.paper = {
          planName: row.planName || "", // 卷名
          questionNum: row.questionNum || 5, // 总题数，设置默认值
          passScore: row.passScore || 60, // 及格分，设置默认值
          remark: row.remark || "", // 备注
          professionId: row.professionId || 1, // 职业ID，设置默认值
          // 其他字段根据需要添加
          createType: row.createType,
          // //回显待选课件
          courseIds: row.courseIds ? row.courseIds.split(',') : [], // 将字符串转换为数组
          // //回显已选课件
          questionIds: row.questionIds ? row.questionIds.split(',') : [], // 将字符串转换为数组
          planId: row.planId
        };
        if (row.createType == '手动') {
          this.showQusiton = false;
        }
        queryCourseByIds({ courseIds: row.courseIds }).then(res => {
          this.checkCour = res.data
        })

        getQuestionListIds({ questionIds: row.questionIds }).then(res => {
          this.checkQu = res.data;
        })

      } else {
        this.dialogVisible = true;
      }
      //获取题库数据
      this.queryQuBankSel();
      //获取章节列表
      this.getSectionList(this.paper.professionId);
    },
    //关闭弹窗
    handleClose() {
      this.dialogVisible = false;
      this.clearData();
    },
    //清空表单
    clearData() {
      this.paper = {
        planName: "",
        questionNum: 5,
        passScore: 60,
        remark: "",
        quBankId: "全部",
        professionId: 1,
        questionIds: [], // 初始化为空数组
      };

      this.checkCour = []; // 清空已选课件
      this.checkQu = []; // 清空已选题目
      this.selectedSection = null; // 清空选中的章节
      this.sectionList = []; // 清空章节列表
    },
    //获取题库下拉框
    queryQuBankSel() {
      getProfessionList()
        .then((res) => {
          for (let s of res.data) {
            this.quBank.push({
              value: s.professionId,
              label: s.professionName,
            });
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    //获取题库试题
    queryQuestion(quBankId) {
      let params = {};
      params.current = 1;
      params.size = 10;
      params.quBankId = quBankId;
      queryQuAll(params).then((res) => {
        this.tableData = res.data.records;
      });
    },

    //更新已选择的课件值
    updateCourse(row) {
      this.checkCour = row;
    },

  },
};
</script>
<style lang="scss" scoped>
.course-table {
  ::v-deep(.el-checkbox_inner) {
    flex: 1;
  }
}

.chapter {
  height: 500px;
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow: auto;

  span {
    width: 274px;
    height: 40px;
    line-height: 40px;
    margin: 10px;
    box-sizing: border-box;
    border: 1px solid black;
    border-radius: 4px;
    color: #606266;
    white-space: nowrap;
    text-overflow: ellipsis;
    text-align: center;
  }

  span.active {
    color: #459ffc;
    background-size: 100% 100%;
    border: 1px solid #459ffc;
  }
}
</style>
